package com.xiaoniu.forum.service.impl;

import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaoniu.forum.common.ali.AliSMSCodeUtil;
import com.xiaoniu.forum.common.utils.IdGen;
import com.xiaoniu.forum.dao.MemberDao;
import com.xiaoniu.forum.entity.MemberEntity;
import com.xiaoniu.forum.form.AppSMSForm;
import com.xiaoniu.forum.renren.common.exception.RRException;
import com.xiaoniu.forum.service.AppSMSService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.crypto.hash.Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class AppSMSServiceImpl implements AppSMSService {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private MemberDao memberDao;

    @Override
    public void sendMessage(String phone) {

        QueryWrapper<MemberEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("username",phone);
        Integer count = memberDao.selectCount(wrapper);
        if (count > 0){
            throw new RRException("手机号已存在！！");
        }

        String code = IdGen.getRandom4Num();
        String redisKey = "MSM:" + phone;

        String redisCode = (String) redisTemplate.opsForValue().get(redisKey);
        if (!StringUtils.isEmpty(redisCode)){
            log.info("从redis中取出验证码:{{}} redis值{{}}",redisCode,redisKey);
            return;
        }

        log.info("发送验证码，并存入redis{}",code);

        redisTemplate.opsForValue().set(redisKey, code, 60L, TimeUnit.MINUTES);

        HashMap<String, Object> map = new HashMap<>();
        map.put("code",code);

        try {
            //发送短信
            AliSMSCodeUtil.getSMSCode(phone, map);
        } catch (ClientException e) {
            e.printStackTrace();
        }
    }
}
